import { VM } from 'vm2';
import { Card } from '../card/base/Card';
import { events } from '../utils/events';
import { logger } from '../utils/logger';
import { existsSync, readFileSync } from 'fs';
import { IModJSON } from './Mod';
import { CardRegistry } from '../registry/CardRegistry';
import { Dept } from '../api/Dept';
import { DeptRegistry } from '../registry/DeptRegistry';
import { GameEndRegistry } from '../registry/GameEndRegistry';
import { CardEvent } from '../api/CardEvent';

export class ScriptLoader {
	constructor(readonly mod: IModJSON) {}

	loadScript(path: string) {
		if (!existsSync(path)) return;

		logger.info(`Loading script: ${path}`);
		const file = readFileSync(path, 'utf-8');

		const vm = new VM({
			sandbox: this.getAPI(),
		});

		vm.run(file);
	}

	private getAPI() {
		const api = {
			// 事件
			events,
			// 卡牌
			Card,
			CardEvent,
			CardRegistry,
			// 部门
			Dept,
			DeptRegistry,
			// 游戏结束
			GameEndRegistry,
		};

		events.emit('api', api);
		Object.keys(api).forEach((key) => {
			logger.info(`Exposed API: ${key}`);
		});

		return api;
	}
}
